﻿using BZ.Logger;
using NDK.Communacation;
using NDK.Module.BLL;
using NDK.Module.Model;
using NDK.Motion.BLL;
using System;
using System.Collections.Generic;
using System.Linq;

namespace NDK.Module.StationLogic
{
    public class StationTCP
    {
        #region 左右工控机通讯
        public static double PPGValue { set; get; }

        /// <summary>
        /// 副站PPG
        /// </summary>
        public static event delegateGetPPG GetPPG;
        public delegate void delegateGetPPG(ReceiveParam e);

        /// <summary>
        /// 副站数据
        /// </summary>
        public static event delegateGetPPG GetData;
        public delegate void delegateGetData(ReceiveParam e);

        public static ECommunacation SeverComputerSocket { set; get; }
        public static ECommunacation ClientComputerSocket { set; get; }

        public static bool StationTCPInit()
        {
            bool ret = true;
            if (Common.Line == "右")
            {
                ret &= ServerInit();

                GetPPG += StationTCP_GetPPG;
                GetData += StationTCP_GetData;
            }
            else
                ret &= ClientInit();
            return ret;
        }

        private static void StationTCP_GetData(ReceiveParam e)
        {
            try
            {
                MeasureProduct measureProduct = new MeasureProduct()
                {
                    SN = e.SN,
                    Position = e.Fixture,
                    whichBlock = Common.whichBlock
                };
                string[] strings = e.Mess.Split(';');
                foreach (string s in strings)
                {
                    if (s.Length > 2)
                    {
                        measureProduct.MeasureData.Add(new DataItem()
                        {
                            Name = s.Split('@')[1],
                            Value = Convert.ToDouble(s.Split('@')[0])
                        });
                    }

                }
                //JUDGEMENT_RESULT ret = ProcessData.PrcessData(measureProduct, false);
                SendStr_SeverComputer($"Data,{e.SN},OK");
            }
            catch (Exception)
            {

            }

        }

        private static void StationTCP_GetPPG(ReceiveParam e)
        {
            double value = 9999;
            try
            {
                value = Machine.PPG.Read("02");
                SendStr_SeverComputer($"PPG,{value}");
            }
            catch (Exception)
            {
                SendStr_SeverComputer($"PPG,{value}");
            }
        }

        public static bool ServerInit()
        {
            SeverComputerSocket = new ECommunacation();
            SeverComputerSocket.LocalPort = Convert.ToInt32(Common.ComputerPort);
            SeverComputerSocket.CommunicationModel = CommunicationModel.TcpServer;
            SeverComputerSocket.ReceiveString += SeverSocket_ReceiveString;
            return SeverComputerSocket.Connect();
        }

        static string clientStr = string.Empty;
        private static void SeverSocket_ReceiveString(string str)
        {
            if (str.Length > 0)
            {
                if (str.StartsWith("START"))
                    clientStr = string.Empty;
                clientStr += str;
                if (!str.EndsWith("END"))
                    return;
                str = clientStr.Replace("START", "");

                string[] strings = str.Trim().Split(new string[] { "END" }, StringSplitOptions.None);
                for (int i = 0; i < strings.Length; i++)
                {
                    if (strings[i].Length > 0)
                    {
                        Common.AppendUiLog.Log($"服务端接收到:{strings[i]}", LogType.Alert);
                        string[] strings1 = strings[i].Split(',');
                        switch (strings1[0])
                        {
                            case "PPG":
                                GetPPG.BeginInvoke(new ReceiveParam() { }, null, null);
                                break;
                            case "Data":
                                GetData.BeginInvoke(new ReceiveParam() { SN = strings1[1], Fixture = strings1[2], Rest = strings[3], Mess = strings1[4] }, null, null);
                                break;
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 左线发送
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool SendStr_SeverComputer(string str)
        {
            bool ret = SeverComputerSocket.SendStr($"{str},#");
            Common.AppendUiLog.Log($"服务端发送请求: {str}信号成功", str.Contains("NG") ? LogType.Error : LogType.Alert);
            return ret;
        }

        public static bool ClientInit()
        {
            ClientComputerSocket = new ECommunacation();
            ClientComputerSocket.RemoteIP = Common.ComputerIP;
            ClientComputerSocket.RemotePort = Convert.ToInt32(Common.ComputerPort);
            ClientComputerSocket.CommunicationModel = CommunicationModel.TcpClient;
            ClientComputerSocket.ReceiveString += ClientSocket_ReceiveString;
            return ClientComputerSocket.Connect();
        }

        private static void ClientSocket_ReceiveString(string str)
        {
            string message = str.Trim();
            string[] strings = message.Trim().Split('#');
            for (int i = 0; i < strings.Length; i++)
            {
                if (strings[i].Length > 0)
                {
                    Common.AppendUiLog.Log($"客户端接收到:{strings[i]}", LogType.Alert);
                    string[] strings1 = strings[i].Split(',');
                    switch (strings1[0])
                    {
                        case "Safedoorsacn":
                            PublicMethod.IsDoorScan = strings1[1] == "ON" ? true : false;
                            break;
                        case "bPLCErrStatus":
                            PublicMethod.bPLCErrStatus = strings1[1] == "ON" ? true : false;
                            break;
                        case "bPLCErrStatus1":
                            PublicMethod.bPLCErrStatus1 = strings1[1] == "ON" ? true : false;
                            break;
                        case "PPG":
                            PPGValue = Convert.ToDouble(strings1[1]);
                            if (PPGValue != 9999)
                                PPGValue = PPGValue + Common.PPGOffset;
                            break;
                        case "Data":
                            foreach (var key in Machine.DicLocalData.Keys)
                            {
                                if (Machine.DicLocalData[key].SN == strings1[1])
                                {
                                    Machine.DicLocalData[key].Result = (JUDGEMENT_RESULT)Enum.Parse(typeof(JUDGEMENT_RESULT), strings1[2]);
                                    PublicMethod.SaveRunImage(Machine.DicLocalData[key]);
                                }
                            }
                            break;
                        case "BlockCheck":
                            if (strings1[1] == "3") Common.BlockCheck1 = strings1[2] == "OK";
                            if (strings1[1] == "4") Common.BlockCheck2 = strings1[2] == "OK";
                            if (strings1[2] != "OK")
                                Common.AppendUiLog.Log($"{strings1[1]}号通道点检失败,请观察当前block物料", LogType.Error);
                            break;
                    }
                }
            }
        }

        /// <summary>
        /// 右线发送
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool SendStr_ClientComputer(string str)
        {
            bool ret = ClientComputerSocket.SendStr($"START{str}END");
            Common.AppendUiLog.Log($"客户端发送请求: {str}信号成功", str.Contains("NG") ? LogType.Error : LogType.Alert);
            return ret;
        }
        #endregion


        #region 与ATL通讯
        public static ECommunacation serverAsyncMes { get; set; }
        public static string StrInCheckStatus_L { set; get; } = "";
        public static string StrInCheckStatus_R { set; get; } = "";

        public static Dictionary<string, string> DicStrOutCheckStatus_L { set; get; }
        public static Dictionary<string, string> DicStrOutCheckStatus_R { set; get; }
        public static void IniMesSever()
        {
            serverAsyncMes = new ECommunacation()
            {
                LocalPort = Convert.ToInt32(Common.ATL_Mes_Port),
                CommunicationModel = CommunicationModel.TcpServer
            };
            serverAsyncMes.Connect();
            serverAsyncMes.ReceiveString += ServerAsyncMes_ReceiveString;
        }

        private static void ServerAsyncMes_ReceiveString(string str)
        {
            if (str.Length > 0)
            {
                string[] strings = str.Split('#');
                for (int i = 0; i < strings.Length; i++)
                {
                    if (strings[i].Length > 1)
                    {
                        string[] strings1 = strings[i].Split(',');
                        Common.AppendUiLog.Log($"Mes_Sever接收:{strings[i]}", strings[i].Contains("OK") ? LogType.Info : LogType.Error);
                        switch (strings1[0])
                        {
                            case "InCheckL":
                                StrInCheckStatus_L = strings1[1];
                                break;
                            case "InCheckR":
                                StrInCheckStatus_R = strings1[1];
                                break;
                            case "OutCheckL":
                                if (DicStrOutCheckStatus_L.Keys.Contains(strings1[1]))
                                    DicStrOutCheckStatus_L[strings1[1]] = strings1[2];
                                else
                                    DicStrOutCheckStatus_L.Add(strings1[1], strings1[2]);
                                break;
                            case "OutCheckR":
                                if (DicStrOutCheckStatus_R.Keys.Contains(strings1[1]))
                                    DicStrOutCheckStatus_R[strings1[1]] = strings1[2];
                                else
                                    DicStrOutCheckStatus_R.Add(strings1[1], strings1[2]);
                                break;
                        }
                    }
                }
            }
        }

        public static void SendMesSever(string str)
        {
            bool isConnected = false;
            try
            {
                isConnected = serverAsyncMes.SendStr($"START{str}END");
                Common.AppendUiLog.Log($"Mes_Sever发送:{str} {(isConnected == true ? "成功" : "失败")}", isConnected == true ? LogType.Info : LogType.Alert);
            }
            catch (Exception ex)
            {
                Common.AppendUiLog.Log($"发送{str}失败：{ex}", LogType.Alert);
            }
        }
        #endregion
    }

    public class ReceiveParam
    {
        public string SN;
        public string Rest;
        public string Fixture = "";
        public string Mess = "";
    }
}
